<template>
    <view class="container">
        <div class="border">
            <div class="border-content">
                <div style="height: 15px;"></div>
                <div class="card">
                    <div style="width: 90%;margin-left: 5%;">
                        <div style="height: 10px;"></div>
                        <div style="font-size: 18px;font-weight: 500;">基础信息</div>
                        <div style="height: 10px;"></div>
                        <u-line color="#f1f1f1"></u-line>
                        <div style="height: 10px;"></div>
                        <div class="newFlex">
                            <div>日期</div>
                            <div>{{ date }}</div>
                        </div>
                        <div style="height: 15px;"></div>
                        <div class="newFlex">
                            <div>时间</div>
                            <div>{{ time }}</div>
                        </div>
                        <div style="height: 15px;"></div>
                        <div class="newFlex">
                            <div>提交人</div>
                            <div>{{ nickName }}</div>
                        </div>
                        <div style="height: 15px;"></div>
                    </div>
                </div>
                <div style="height: 10px;"></div>
                <div class="card">
                    <div style="width: 90%;margin-left: 5%;">
                        <div style="height: 10px;"></div>
                        <div style="font-size: 18px;font-weight: 500;">{{ indent == '维保' ? '报停信息' : '报备信息' }}</div>
                        <div style="height: 10px;"></div>
                        <u-line color="#f1f1f1"></u-line>
                        <div style="height: 10px;"></div>
                        <div v-if="indent == '知识库'">
                            <div>生产部门</div>
                            <div style="height: 15rpx;"></div>
                            <div class="borders">
                                <picker @change="bindDeptChange" :value="index" :range="deplist">
                                    <input style="height: 42px;" type="text" v-model="deptName" placeholder="请选择生产部门" disabled>
                                </picker>
                            </div>
                        </div>
                        <div style="height: 15px;"></div>
                        <div>
                            <div>设备名称</div>
                            <div style="height: 15rpx;"></div>
                            <div class="borders">
                                <picker @change="bindPickerChange" :value="index" :range="deList">
                                    <input style="height: 42px;" type="text" v-model="deviceName" placeholder="请选择设备" disabled>
                                </picker>
                            </div>
                        </div>
                        <div style="height: 15px;"></div>
                        <div v-if="indent == '维保'">
                            <div>报停时长（小时）</div>
                            <div style="height: 15rpx;"></div>
                            <div class="borders">
                                <input style="height: 42px;" type="text" v-model="stopDuration" placeholder="请输入内容">
                            </div>
                        </div>
                        <div v-if="indent == '维保'" style="height: 15px;"></div>
                        <div>
                            <div>{{ indent == '维保' ? '报停原因' : indent == '巡检' ? '报修原因' : '生产描述' }}</div>
                            <div style="height: 15rpx;"></div>
                            <div class="borders">
                                <input style="height: 42px;" v-if="indent!='知识库'" v-model="reasonStop" type="text"
                                    :placeholder="indent == '维保' ? '报停原因' : indent == '巡检' ? '报修原因' : ''">
                                    <input style="height: 42px;" v-if="indent=='知识库'" v-model="productionDescrip" type="text"  placeholder="请输入内容">
                            </div>
                        </div>
                        <div style="height: 15px;"></div>
                        <div v-if="indent == '维保'">
                            <div>报停详情</div>
                            <div style="height: 15rpx;"></div>
                            <div class="borders">
                                <input style="height: 42px;" v-model="description" type="text" placeholder="请输入报停详情">
                            </div>
                        </div>
                        <div v-if="indent == '巡检'">
                            <div>紧急程度</div>
                            <div style="height: 15rpx;"></div>
                            <div class="borders">
                                <picker @change="bindDegree" :value="index" :range="degreeList">
                                    <input style="height: 42px;" type="text" v-model="emerDegree" placeholder="请选择紧急程度" disabled>
                                </picker>
                            </div>
                        </div>
                        <div style="height: 15px;"></div>
                        <div v-if="indent != '知识库'">
                            <div>现场照片（图1）</div>
                            <div style="height: 15rpx;"></div>
                            <u-upload :capture="['camera']" :fileList="fileList1" @afterRead="afterRead"
                                @delete="deletePic" name="1" multiple :maxCount="1" width="150" height="150">
                            </u-upload>
                        </div>
                        <div v-if="indent != '知识库'" style="height: 15px;"></div>
                        <div v-if="indent != '知识库'">
                            <div>现场照片（图2）</div>
                            <div style="height: 15rpx;"></div>
                            <u-upload :capture="['camera']" :fileList="fileList2" @afterRead="afterReads"
                                @delete="deletePics" name="2" multiple :maxCount="1" width="150" height="150">
                            </u-upload>
                        </div>
                        <div v-if="indent != '知识库'" style="height: 15px;"></div>
                    </div>
                    <div class="footer">
                        <div class="button-footer" @click="submitInfo">提交</div>
                    </div>
                    <div style="height: 15px;"></div>
                </div>
                <!-- 表单 -->
                <!-- <div style="color: #718778;">
                    <div class="form-flex" v-if="indent=='知识库'">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">生产部门</div>
                        <div class="borders">
                            <div style="height: 5rpx;"></div>
                            <picker @change="bindDeptChange" :value="index" :range="deplist">
                                <input type="text" v-model="deptName" placeholder="请选择生产部门" disabled>
					        </picker>
                            <div style="height: 5rpx;"></div>
                        </div>
                    </div>
                    <div style="height: 10px;"></div>
                    <div v-if="indent=='知识库'" style="display: flex;align-items: center;">
                        <div style="display: flex;width: 20%;">
                            <div style="color: #1A512C;font-weight: 500;">生产描述</div>
                        </div>
                        <div style="width: 1%;"></div>
                        <div class="borders" style="width: 79%"><u--textarea
                                v-model="productionDescrip"></u--textarea></div>
                    </div>
                    <div style="height: 10px;"></div>
                    <div v-if="indent=='巡检'">
                        <div style="height: 10px;"></div>
                    <div class="form-flex">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">紧急程度</div>
                        <div class="borders">
                            <div style="height: 5rpx;"></div>
                            <picker @change="bindDegree" :value="index" :range="degreeList">
                                <input type="text" placeholder-class="holder-class" v-model="emerDegree" placeholder="请选择紧急程度" disabled>
					        </picker>
                            <div style="height: 5rpx;"></div>
                        </div>
                    </div>
                    </div>
                    <div style="height: 10px;"></div>
                    </div>
                    </div>

                    <div style="height: 10px;"></div>
                </div> -->
                <!-- 按钮 -->
                <div style="height: 10px;"></div>

            </div>
        </div>
    </view>
</template>
<script>
import { deviceList, addStop, addRepair, addBase, deptList } from '../api/api.js';
import request from '../../common/request';
export default {
    data() {
        const currentDate = this.getDate({
            format: true
        })
        return {
            degreeList: ['一般紧急', '很紧急', '非常紧急'],
            date: currentDate,
            time: '',
            faultCause: '',//报停原因
            faultDuration: '',//时长
            deviceName: '',
            nickName: '',
            fileList1: [],
            fileList2: [],
            img1: '',
            img2: '',
            base: '',
            request: request,
            deList: [],
            deSeaList: [],
            deviceId: '',
            description: '',
            stopDuration: '',
            indent: '',
            emerDegree: '',
            productionDescrip: '',
            deplist: [],
            seaDeplist: [],
            deptName: '',
            deptId: ''
        }
    },
    methods: {
        // 返回
        cancel() {
            uni.navigateBack({ delta: 1 })
        },
        bindDateChange: function (e) { //选择日期
            this.date = e.detail.value
            console.log('date', this.date)
        },
        getDate(type) { //年月日
            const date = new Date();
            // const date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();

            if (type === 'start') {
                year = year - 60;
            } else if (type === 'end') {
                year = year + 2;
            }
            month = month > 9 ? month : '0' + month;
            day = day > 9 ? day : '0' + day;
            return `${year}-${month}-${day}`;
        },
        getTime() {
            const now = new Date();
            const hours = now.getHours();
            const minutes = now.getMinutes();
            // this.time = hours + ':' + minutes
        },
        // 提交
        submitInfo() {
            if (this.indent == '维保') {
                if (this.img1 == '' || this.img2 == '' || this.deviceId == '' || this.stopDuration == '') {
                    uni.showToast({
                        title: '输入完整后提交',
                        icon: 'none'
                    })
                } else {
                    let combinedString = `${this.img1},${this.img2}`;
                    console.log(combinedString);
                    addStop({
                        stopTime: this.date + ' ' + this.time,
                        submitPeople: this.nickName,
                        deviceId: this.deviceId,
                        deviceName: this.deviceName,
                        stopDuration: this.stopDuration,
                        devicePhoto: combinedString,
                        stopDurationUnit: 'h',
                        reasonStop: this.reasonStop,
                        description: this.description
                    }).then(res => {
                        console.log(res, 'add');
                        if (res.data.code == 200) {
                            uni.showToast({
                                title: res.data.msg,
                                icon: 'success',
                                mask: true
                            });
                            setTimeout(() => {
                                this.closeForm();
                                uni.navigateBack({ delta: 1 })
                            }, 1000)
                        } else {
                            uni.showToast({
                                title: res.data.msg,
                                icon: 'none',
                                mask: true
                            })
                        }
                    })
                }
            } else if (this.indent == '巡检') {
                if (this.deviceId == '' || this.img1 == '' || this.img2 == '' || this.emerDegree == '' || this.reasonStop == '') {
                    uni.showToast({
                        title: '输入完整后提交',
                        icon: 'none'
                    });
                } else {
                    let combinedString = `${this.img1},${this.img2}`;
                    addRepair({
                        deviceId: this.deviceId,
                        deviceName: this.deviceName,
                        subPeople: this.nickName,
                        scenePhoto: combinedString,
                        emerDegree: this.emerDegree,
                        detailDescription: this.reasonStop
                    }).then(res => {
                        console.log(res.data, '巡检报修');
                        if (res.data.code == 200) {
                            uni.showToast({
                                title: res.data.msg
                            })
                            setTimeout(() => {
                                this.closeForm();
                                uni.navigateBack({ delta: 1 })
                            }, 1000)
                        } else {
                            uni.showToast({
                                title: res.data.msg,
                                icon: 'none'
                            })
                        }
                    })
                }

            } else {
                //知识库
                addBase({
                    deptId: 1,
                    deptName: 1,
                    userId: uni.getStorageSync('userInfo').userId,
                    subPerson: this.nickName,
                    deviceId: this.deviceId,
                    deviceName: this.deviceName,
                    deviceArea: 1,
                    productionDescrip: this.productionDescrip,
                    filingTime: this.date + ' ' + this.time,
                    isRead: 1
                }).then(res => {
                    console.log(res.data);
                    if (res.data.code == 200) {
                        uni.showToast({
                            title: res.data.msg
                        })
                        setTimeout(() => {
                            this.closeForm();
                            uni.navigateBack({ delta: 1 })
                        }, 1000)
                    } else {
                        uni.showToast({
                            title: res.data.msg,
                            icon: 'none'
                        })
                    }
                })
            }


        },
        //
        deletePic(event) {
            this[`fileList${event.name}`].splice(event.index, 1)
        },
        deletePics(event) {
            this[`fileList${event.name}`].splice(event.index, 1)
        },
        // 新增图片
        async afterRead(event) {
            console.log(event);
            let lists = [].concat(event.file)
            let fileListLen = this[`fileList${event.name}`].length
            lists.map((item) => {
                this[`fileList${event.name}`].push({
                    ...item,
                    status: 'uploading',
                    message: '上传中'
                })
            })
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i].url)
                let item = this[`fileList${event.name}`][fileListLen]
                this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
                    status: 'success',
                    message: '',
                    url: result
                }))
                fileListLen++
            }
        },
        async afterReads(event) {
            console.log(event);
            let lists = [].concat(event.file)
            let fileListLen = this[`fileList${event.name}`].length
            lists.map((item) => {
                this[`fileList${event.name}`].push({
                    ...item,
                    status: 'uploading',
                    message: '上传中'
                })
            })
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromises(lists[i].url)
                let item = this[`fileList${event.name}`][fileListLen]
                this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
                    status: 'success',
                    message: '',
                    url: result
                }))
                fileListLen++
            }
        },
        uploadFilePromise(url) {
            return new Promise((resolve, reject) => {
                let a = uni.uploadFile({
                    url: `${this.base}/file-upload/single`,
                    filePath: url,
                    name: 'file',
                    formData: {
                        'type': 'faultPhoto'
                    },
                    header: {
                        Authorization: uni.getStorageSync('token')
                    },
                    success: (res) => {
                        const data = JSON.parse(res.data)
                        console.log(data);
                        this.img1 = data.data;
                        resolve(res.data.data)
                    }
                });
            })
        },
        getDevice() {
            deviceList().then(res => {
                console.log(res.data.rows, '设备列表');
                this.deList = res.data.rows.map((item) => item.deviceName);
                this.deSeaList = res.data.rows;
            })
        },
        getDept() {
            deptList().then(res => {
                console.log(res.data, '部门列表');
                this.deplist = res.data.rows.map((item) => item.deptName);
                this.seaDeplist = res.data.rows;
            })
        },
        bindDeptChange(e) {
            const value = e.detail.value;
            this.deptName = this.seaDeplist[value].deptName;
            this.deptId = this.seaDeplist[value].id;
        },
        uploadFilePromises(url) {
            return new Promise((resolve, reject) => {
                let a = uni.uploadFile({
                    url: `${this.base}/file-upload/single`,
                    filePath: url,
                    name: 'file',
                    formData: {
                        'type': 'faultPhoto'
                    },
                    header: {
                        Authorization: uni.getStorageSync('token')
                    },
                    success: (res) => {
                        const data = JSON.parse(res.data)
                        console.log(data, 'data2');
                        this.img2 = data.data;
                        resolve(res.data.data)
                    }
                });
            })
        },
        closeForm() {
            this.img1 = '';
            this.img2 = '';
            this.fileList1 = [];
            this.fileList2 = [];
            this.faultCause = '';
            this.stopDuration = '';
            this.deviceName = '';
            this.deviceId = '';
            this.stopDuration = '';
            this.reasonStop = '';
            this.description = '';
            this.emerDegree = '';
        },
        bindPickerChange: function (e) {
            console.log('picker发送选择改变，携带值为', e.detail.value)
            const value = e.detail.value;
            this.deviceName = this.deSeaList[value].deviceName;
            this.deviceId = this.deSeaList[value].id;
        },
        bindDegree(e) {
            const value = e.detail.value;
            this.emerDegree = this.degreeList[value];
        }
    },
    onShow() {
        this.getTime();
        this.getDevice();
        this.getDept();
        this.nickName = uni.getStorageSync('userInfo').nickName
        this.base = this.request.config.baseURL;
        this.indent = uni.getStorageSync('pageIndent');
        let now = new Date();
        let hours = now.getHours().toString().padStart(2, '0');
        let minutes = now.getMinutes().toString().padStart(2, '0');
        let seconds = now.getSeconds().toString().padStart(2, '0');
        let currentTime = `${hours}:${minutes}:${seconds}`;
        this.time = currentTime;
    }
}
</script>
<style lang="scss">
.newFlex {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.card {
    background: #fff;
    border-radius: 10px;
}

.container {
    background: #f3f3f3;

    .border {
        background: #f3f3f3;
        height: 100vh;
        overflow-y: scroll;

        .border-content {
            width: 90%;
            margin-left: 5%;
        }
    }
}

.top-line {
    display: flex;
    align-items: center;
}

.line {
    background: #1A512C;
    width: 7rpx;
    height: 35rpx;
}

.form-flex {
    display: flex;
    align-items: center;
    width: 100%;
}

.borders {
    border: 1px solid #9e9e9e;
    border-radius: 5px;
    text-align: center;
}

.borders-min {
    border: 1px solid #1A512C;
    border-radius: 5px;
    text-align: center;
}

.footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.button-footer {
    width: 80%;
    margin-left: 10%;
    height: 50px;
    background: #000000;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 18px;
    font-weight: 500;
    border-radius: 10px;
}

.top {
    width: 224rpx;
    height: 224rpx;
    margin: 0 auto;
    margin-bottom: 50rpx;
    margin-top: 50rpx;
    border: 1px solid red;

    image {
        width: 224rpx;
        height: 224rpx;
        border-radius: 50%;
    }

    .tips {
        font-size: 28rpx;
    }
}
</style>
<style>
.holder-class {
    color: #1A512C;
}
</style>